import axios from 'axios';
import { layer } from '@/components/vue2-layer-mobile';
import { getToken } from '@/utils/auth';
import store from '@/store';
const domainArr = document.domain.split('.')
// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API, // api 的 base_url
  timeout: 50000 ,// 请求超时时间
	headers: {
		'Pay-Domain': document.domain.indexOf('9ox.cn') !== -1 ? '9ox.cn' : '1234tv.com'
	},
});
let layerIndex;
// request拦截器
service.interceptors.request.use(
  config => {
		if(window['Pay-Token']){
			config.headers.Authorization = window['Pay-Token']
		}else if(store.getters.token) {
      config.headers.Authorization = store.getters.token // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code === 401) {
      if (store.getters.user && store.getters.user.logined) {
        store.dispatch('Refresh').then(() => {
        }).catch(err => {
          console.log(err);
        });
      } else {
				layer.open({
				  content: res.message,
				  skin: 'msg',
				  time: 2,
				});
        store.dispatch('FedLogOut').then(() => {})
				return Promise.reject(res)
      }
    } else if (res.code && res.code !== 0) {
      if (res.data && res.data.message && Array.isArray(res.data.message)) {
        layer.open({
          content: res.data.message[0],
          skin: 'msg',
          time: 2 // 2秒后自动关闭
        });
      }else if(res.code === 1000020 || res.code === 1000021){
				layer.open({
				  content: res.message,
				  skin: 'msg',
				  time: 1 ,// 2秒后自动关闭
					end(){
						location.href = '/'
					}
				});
			}else if (res.code !== 1000010 && res.code !== 1000011 && res.code !== 1000002 && res.code !== 1000013 && res.code !== 1000017 && res.code !== 1000016) {
        layer.open({
          content: res.message,
          skin: 'msg',
          time: 2 // 2秒后自动关闭
        });
      }
      return Promise.reject(res);
    } else {
      return response.data;
    }
  },
  error => {
    console.log(error);
    return Promise.reject(error);
  }
);

export default service;
